﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

using Museum.DBAccess;

public partial class CityDetails : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!Page.IsPostBack)
            {
                ddlCountry.DataSource = DBAccess.GetAllCountries();
                ddlCountry.DataBind();

                ddlCountry.Items.FindByText("United States").Selected = true;

                if (Request.QueryString["CityID"] != null)
                    BindCityData();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int cityId = 0;
        try
        {
            if (Request.QueryString["CityID"] != null)
                cityId = Convert.ToInt32(Request.QueryString["CityID"]);

            if (txtCityName.Text.Trim().Length > 0)
            {
                DBAccess.InsertOrUpdateCityDetails(Convert.ToInt32(ddlCountry.SelectedItem.Value), txtCityName.Text.Trim(), cityId);

                if (cityId < 1)
                {
                    Alert.ShowMessage("City inserted successfully.");
                    Response.Redirect("ManageCity.aspx", false);
                }
                else
                    Alert.ShowMessage("City updated successfully.");
            }
        }
        catch (Exception ex)
        {
            Alert.ShowMessage("Some error occurred, please try again.");
            throw ex;
        }
        ClearControls();
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        ClearControls();
    }
    private void ClearControls()
    {
        txtCityName.Text = "";
    }

    private void BindCityData()
    {
        DataRow[] dtRows = null;
        DataTable dtCities = null;
        DataTable dtNewCities = null;
        try
        {
            dtCities = DBAccess.GetAllCities();

            dtRows = dtCities.Select("CityId=" + Request.QueryString["CityID"]);

            dtNewCities = dtCities.Clone();
            foreach (DataRow row in dtRows)
            {
                dtNewCities.ImportRow(row);
            }
            if (dtNewCities != null && dtNewCities.Rows.Count > 0)
            {
                txtCityName.Text = dtNewCities.Rows[0]["CityName"].ToString();
                ddlCountry.SelectedValue = dtNewCities.Rows[0]["CountryId"].ToString();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}